package com.enjoy.nettyhttp.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * 基于netty 实现一个web服务器
 * Created by HP on 2019/7/15.
 */
public class HttpServer {
    public static final int port = 6789; //设置服务端端口
    private static EventLoopGroup group = new NioEventLoopGroup();   // 通过nio方式来接收连接和处理连接
    private static ServerBootstrap b = new ServerBootstrap();
    private static final boolean SSL = true;

    public static void main(String[] args) throws Exception {
        final SslContext sslCtx ;
        if (SSL){
            SelfSignedCertificate ssc=new SelfSignedCertificate();
            sslCtx= SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();
        }else {
            sslCtx=null;
        }
        try {
            b.group(group);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ServerHandlerInit(sslCtx));
            //服务端绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务端启动成功：" + port);
            f.channel().closeFuture().sync();
        } finally

        {
            group.shutdownGracefully();
        }
    }
}
